package com.ruoyi.web.controller.backstage;

import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysShortUrl;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.HrWebServiceUtil;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.ShotUrlUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.system.domain.SysSsoConfigVo;
import com.ruoyi.system.domain.WorkItemPend;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.service.ISysShortUrlService;
import com.ruoyi.system.service.ISysSsoConfigVoService;
import com.ruoyi.system.service.IWorkItemPendService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 流程中心 controller类
 * cjj
 */
@RequestMapping("/system/process")
@RestController
public class SysProcessCenterController extends BaseController{


    @Value("${interfaceAddress.hrWebServiceUrl}")
    public String hrWebServiceUrl;

    @Value("${interfaceAddress.portalAddress}")
    public String portalAddress;

    @Autowired
    private IWorkItemPendService workItemPendService;

    @Resource
    private TokenService tokenService;

    @Resource
    private ISysDeptService sysDeptService;

    @Resource
    private ISysShortUrlService iSysShortUrlService;

    @Autowired
    private ISysSsoConfigVoService sysSsoConfigVOService;
    /**
     * 查询待办待阅分页列表
     */
    @GetMapping("/list")
    public TableDataInfo list(WorkItemPend workItemPend)
    {
        //发起部门解析
        if(StringUtils.isNotBlank(workItemPend.getPromoterOrg())){
            List<SysDept> sysDepts = sysDeptService.getChildListByDeptId(workItemPend.getPromoterOrg());
            List<String> sysDeptStrs = sysDepts.stream().map(SysDept::getDeptName).collect(Collectors.toList());
            workItemPend.setPromoterOrgs(sysDeptStrs);
        }
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        workItemPend.setReceiverUserCode(loginUser.getUser().getUserNo());
        startPage();
        List<WorkItemPend> list = workItemPendService.selectWorkItemPendList(workItemPend);
        return getDataTable(list);
    }

    /**
     * 查询待办待阅统计数量
     */
    @GetMapping("/count")
    public AjaxResult count(WorkItemPend workItemPend)
    {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        if (loginUser != null && loginUser.getUser() != null && loginUser.getUser().getUserNo() != null) {
            String userNo = loginUser.getUser().getUserNo();
            workItemPend.setReceiverUserCode(userNo);
        }
        return AjaxResult.success(workItemPendService.selectCountWorkItemPend(workItemPend));
    }

    /**
     * 获取待办待阅跳转链接
     * @param id
     * @return
     */
    @GetMapping("/getJumpLink")
    @ApiOperation(value = "流程跳转", notes = "待办待阅跳转")
    public AjaxResult processjump(Long id, HttpServletRequest request) {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        Object url = "";
        String userNo = loginUser.getUser().getUserNo();
        if(null==id){
             return AjaxResult.error("参数为null");
        }
        Map<String, String> urlMap = new HashMap<>(2);
        WorkItemPend workItemPend = workItemPendService.selectWorkItemPendAndSSOById(id);
        SysSsoConfigVo sysSsoConfigVo = sysSsoConfigVOService.selectSysSsoConfigVOByName(workItemPend.getSystemName());
        if(Constants.SYSTEM_Portal.equals(workItemPend.getSystemName())){
            url = workItemPend.getPcUrl()+"&code="+userNo;
        }else{
            //单点登陆类型(1=token登陆，2=token通用，3=模拟登陆)
            if(("1").equals(workItemPend.getSsoType())){
                if(Constants.SYSTEM_HR.equals(workItemPend.getSystemName())){
                    //TODO 调用Hr获取token方法
                    String token = HrWebServiceUtil.getHrToken(userNo, 0,hrWebServiceUrl);
                /*url =  workItemPend.getSsoUrl()+"?Token="+token+
                        "&toLink="+ URLEncoder.encode(workItemPend.getPcUrl());*/
                    url = workItemPend.getPcUrl();
                }else if(Constants.SYSTEM_EC.equals(workItemPend.getSystemName())){
                    url = workItemPend.getPcUrl()+"&code="+userNo;
                }
            }else if(("2").equals(workItemPend.getSsoType())){
                String systemToken = tokenService.getToken(ServletUtils.getRequest());
                if(Constants.SYSTEM_OA.equals(workItemPend.getSystemName())){
                    url =  workItemPend.getSsoUrl()+"?token="+systemToken+
                            "&toLink="+ URLEncoder.encode(workItemPend.getPcUrl());
                }else{
                    url =  workItemPend.getSsoUrl()+"?token="+systemToken+
                            "&toLink="+ workItemPend.getPcUrl();
                }
            }
        }
        if (null!=sysSsoConfigVo && "1".equals(sysSsoConfigVo.getOpenWay())){
            String ssoUrl = url.toString();
            String ssoShotUrl = ShotUrlUtils.generatorShortUrl(ssoUrl);
            SysShortUrl sysShortUrl = new SysShortUrl();
            sysShortUrl.setCreateBy(userNo);
            sysShortUrl.setShortUrl(ssoShotUrl);
            sysShortUrl.setSrcUrl(ssoUrl);
            iSysShortUrlService.insertSysShortUrl(sysShortUrl);
            urlMap.put("URL", portalAddress+"/link/"+ssoShotUrl);
        }else {
            urlMap.put("URL", url.toString());
        }
        if(null!=sysSsoConfigVo){
            urlMap.put("openWay",sysSsoConfigVo.getOpenWay());
        }else{
            urlMap.put("openWay", "0");
        }
        return AjaxResult.success("成功",urlMap);
    }

}
